import { computed, ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import dayjs from 'dayjs'

export function useObserve (apiFn) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target, ([{ isIntersecting }], observerElement) => {
      console.log('我出现在可视区域了', isIntersecting)
      if (isIntersecting) {
        apiFn()
        // 当 请求一次之后 停止 监听 防止二次请求
        stop()
      }
    }
  )
  return target
}
// 倒计时 插件  换一种希纳是方式 mm分ss秒
export function useCountDown (startCount) {
  const time = ref(0)
  // 准备一个计算属性 基于原来的数字, 解析成xx分xx秒
  const countTimeTest = computed(() => {
    return dayjs.unix(time.value).format('mm分ss秒')
  })

  const { pause, resume } = useIntervalFn(() => {
    if (time.value <= 0) {
      pause()
      return
    }
    time.value--
  }, 1000)
  const start = (newStartCount) => {
    time.value = newStartCount || startCount
    resume()
  }
  return {
    time,
    countTimeTest,
    start,
    pause,
    resume
  }
}
